/*
 *
 *  *    Copyright © OpenAtom Foundation.
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *         http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.inspur.edp.commonmodel.engine.api.common;

import com.inspur.edp.commonmodel.engine.api.exception.CMEngineException;
import com.inspur.edp.commonmodel.engine.api.exception.ErrorCodes;
import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataCustomizationFilter;
import com.inspur.edp.lcm.metadata.api.service.MetadataRTService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

public class CMEngineUtil {

    private static volatile MetadataRTService mdSvr;

    public static MetadataRTService getMetadataRTSvr() {
        if (mdSvr == null) {
            mdSvr = SpringBeanUtils.getBean(MetadataRTService.class);
        }
        return mdSvr;
    }

    public static GspMetadata getMetadata(String id) {
        MetadataCustomizationFilter filter = new MetadataCustomizationFilter();
        filter.setMetadataId(id);
        filter.setIsI18n(false);
        return getMetadataRTSvr().getMetadata(filter);
    }

    public static <T extends IMetadataContent> T getMetadataContent(String id) {
        try {
            GspMetadata meta = getMetadata(id);
            return meta == null ? null : (T) meta.getContent();
        } catch (Throwable t) {
            throw new CMEngineException(new Exception(t), ErrorCodes.CM_ENGINE_0003, id);
        }
    }
}
